package com.laikan.reader.bookreader.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.core.utils.FileUtil;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;

import java.io.File;
import java.lang.reflect.Type;

/**
 * Created by wx on 16/8/22.
 * 章节util
 * 章节保存
 * 章节读取
 * 章节加密
 */
public class ChapterUtil {

    //获取文件夹得根目录
    private static File file = PublicUtil.getRootPath();
    //获取章节文件对应的路径
    private static String chapterPath = "";
    //章节加密秘钥
    public static String EFS_KEY = "123456789012345678901234567890123456789088888888";
    //来看书籍目录
    private static String LAIKAN_FILE_DIR = PublicUtil.getRootPath().getPath()+"/LaikanReader/book/";

    /**
     * 从本地文件获取章节数据
     * @param bookid
     * @return BaseDataBean<BookChapterBean<ChapterBean>>
     *    [...
     *      {"id": 890732,
     *      "free": false,
     *      "volumeId": 9618,
     *      "name": "第448章 大结局·（上）",
     *      "volume": false},
     *      ...]
     */
    public static BaseDataBean<BaseListDataBean<ChapterBean>> getChapterDataFromLocal(String bookid) {

        BaseDataBean<BaseListDataBean<ChapterBean>> result = null;
        if (setChapterPath(bookid).exists()) {
            String json = FileUtil.readFileString(chapterPath);
            KLog.json(json);
            Gson gson = new Gson();
            Type type = new TypeToken<BaseDataBean<BaseListDataBean<ChapterBean>>>() {}.getType();
            result = gson.fromJson(json, type);
        }
        return result;
    }

    /**
     * 保存章节目录
     *
     * @param json
     * @param bookid
     */
    public static void saveChapter(String json, String bookid) {
        if (!setChapterPath(bookid).isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        FileUtil.writeFile(chapterPath, json);
    }

    /**
     * 设置文件路径
     *
     * @param booksid
     */
    private static File setChapterPath(String booksid) {
        chapterPath = file.getPath() + "/LaikanReader/book/" + booksid + "/chapter";
        return new File(chapterPath);
    }

    /**
     * 通过BookID和章节id获取章节所在路径
     * @return
     */
    public static String getChapterPath_BookId(String bookId,String chapterId){
        return LAIKAN_FILE_DIR+ bookId + "/" + chapterId;
    }
    /**
     * 通过BookID获取书籍所在路径
     * @return
     */
    public static String getBookPath(String bookId){
        return LAIKAN_FILE_DIR + bookId+"/";
    }

}
